import router from './index'
import store from '@/utils/store'
import { getRouter } from '@/api/api'
import { routerMap } from '@/assets/routerMap.js'
import { getItem } from '@/utils/utils.js'

const routerExt = [
  {
    path: '*',
    redirect: '/404'
  }
]

// 异步加载路由
router.beforeEach( (to, from, next) => {
  const token = getItem('token')//判断登录状态
  if (token) {
    if (to.path === '/login') {
      next({path:'/home'})
    } else {
      if (!store.state.isInitRoute) {
        getRouter().then(res=>{
          let asycRoute = createrRoute(res).concat(routerExt)
          router.addRoutes(asycRoute)
          store.state.isInitRoute = true;
        }) 
      }
      next()
    }
  }else{
    next(to.path !== '/login' ? { path: '/login' } : true)
  }
  
  
})



// 遍历数据将componet路径转为组件
const createrRoute = (routes)=>{
  return routes.reduce((prev, cur) => {
    prev.push({
      ...cur,
      component: routerMap[cur.component],
      children: cur.children?createrRoute(cur.children):[]
    })
    return prev
  }, [])
}

